package com.wanghe.others;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 1. 两数之和
 * https://leetcode-cn.com/problems/two-sum/
 */
public class Problem01 {

    public static void main(String[] args) {
        Problem01 p = new Problem01();
        int[] nums = new int[]{2, 7, 11, 15};
        int target = 9;
        System.out.println(Arrays.toString(p.twoSum(nums, target)));
    }

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> numMap = new HashMap<>();
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int n = nums[i];
            int diff = target - n;
            Integer v = numMap.get(diff);
            if (null == v) {
                numMap.put(n, i);
            } else {
                result[0] = v;
                result[1] = i;
                return result;
            }
        }
        return null;
    }

}
